<template>
  <a-config-provider :locale="locale">
    <a-card :bordered="false">
      <!-- 查询区域 -->
      <div class="table-page-search-wrapper">
        <!-- 搜索区域 -->
        <a-form layout="inline" @keyup.enter.native="searchQuery">
          <a-row :gutter="24">
            <a-col :md="6" :sm="24">
              <a-form-item label="单据编号" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-input placeholder="请输入单据编号" v-model="queryParam.number"></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="单据日期" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-range-picker
                  style="width: 100%"
                  v-model="queryParam.createTimeRange"
                  format="YYYY-MM-DD"
                  :placeholder="['开始时间', '结束时间']"
                  @change="onDateChange"
                />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
                <a-button type="primary" @click="searchQuery">查询</a-button>
                <a-button style="margin-left: 8px" v-print="'#reportPrint'" icon="printer">打印</a-button>
                <a-button style="margin-left: 8px" @click="exportExcel" icon="download">导出</a-button>
                <a @click="handleToggleSearch" style="margin-left: 8px">
                  {{ toggleSearchStatus ? '收起' : '展开' }}
                  <a-icon :type="toggleSearchStatus ? 'up' : 'down'"/>
                </a>
              </span>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item>
                <span>总数量：{{operNumberSum}}，总利润：{{profitPriceSum}}</span>
              </a-form-item>
            </a-col>
            <template v-if="toggleSearchStatus">
              <a-col :md="6" :sm="24">
                <a-form-item label="商品" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input placeholder="请输入条码、名称、助记码、规格、型号等信息" v-model="queryParam.materialParam"></a-input>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="客户" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-select placeholder="请选择客户" v-model="queryParam.organId"
                            :dropdownMatchSelectWidth="false" showSearch allow-clear optionFilterProp="children">
                    <a-select-option v-for="(item,index) in cusList" :key="index" :value="item.id">
                      {{ item.supplier }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="仓库" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-select
                    optionFilterProp="children"
                    :dropdownMatchSelectWidth="false"
                    showSearch allow-clear style="width: 100%"
                    placeholder="请选择仓库"
                    v-model="queryParam.depotId">
                    <a-select-option v-for="(depot,index) in depotList" :value="depot.id" :key="index">
                      {{ depot.depotName }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24" v-if="orgaTree.length">
                <a-form-item label="机构" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-tree-select style="width:100%" allow-clear :treeData="orgaTree"
                                 v-model="queryParam.organizationId" placeholder="请选择机构">
                  </a-tree-select>
                </a-form-item>
              </a-col>
            </template>
          </a-row>
        </a-form>
      </div>
      <!-- table区域-begin -->
      <div style="width:100%; min-width:1550px">
        <section ref="print" id="reportPrint">
          <a-table
            bordered
            ref="table"
            size="middle"
            rowKey="id"
            :columns="columns"
            :dataSource="dataSource"
            :components="handleDrag(columns)"
            :pagination="false"
            :loading="loading"
            @change="handleTableChange">
            <span slot="customTitle">
              <a-popover trigger="click" placement="right">
                <template slot="content">
                  <a-checkbox-group @change="onColChange" v-model="settingDataIndex" :defaultValue="settingDataIndex">
                    <a-row style="width: 600px">
                      <template v-for="(item,index) in defColumns">
                        <template>
                          <a-col :span="6">
                            <a-checkbox :value="item.dataIndex" v-if="item.dataIndex==='rowIndex'" disabled></a-checkbox>
                            <a-checkbox :value="item.dataIndex" v-if="item.dataIndex!=='rowIndex'">
                              <j-ellipsis :value="item.title" :length="10"></j-ellipsis>
                            </a-checkbox>
                          </a-col>
                        </template>
                      </template>
                    </a-row>
                    <a-row style="padding-top: 10px;">
                      <a-col>
                        恢复默认列配置：<a-button @click="handleRestDefault" type="link" size="small">恢复默认</a-button>
                      </a-col>
                    </a-row>
                  </a-checkbox-group>
                </template>
                <a-icon type="setting" />
              </a-popover>
            </span>
            <span slot="numberCustomRender" slot-scope="text, record">
              <a @click="myHandleDetail(record)">{{record.number}}</a>
            </span>
          </a-table>
          <a-row :gutter="24" style="margin-top: 8px;text-align:right;">
            <a-col :md="24" :sm="24">
              <a-pagination @change="paginationChange" @showSizeChange="paginationShowSizeChange"
                size="small"
                show-size-changer
                :showQuickJumper="true"
                :page-size="ipagination.pageSize"
                :page-size-options="ipagination.pageSizeOptions"
                :total="ipagination.total"
                :show-total="(total, range) => `共 ${ipagination.oldTotal} 条`">
                <template slot="buildOptionText" slot-scope="props">
                  <span>{{ props.value-1 }}条/页</span>
                </template>
              </a-pagination>
            </a-col>
          </a-row>
        </section>
      </div>
      <!-- table区域-end -->
      <bill-detail ref="modalDetail"></bill-detail>
    </a-card>
  </a-config-provider>
</template>

<script>
  import zhCN from 'ant-design-vue/lib/locale-provider/zh_CN'
  import BillDetail from '@/components/tools/BillDetail'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import { updateTheme } from '@/components/tools/setting'
  import { DEFAULT_COLOR } from "@/store/mutation-types"
  import {findBySelectCus, findBillDetailByNumber, getAllOrganizationTreeByUser} from '@/api/api'
  import { getFormatDate, getPrevMonthFormatDate } from '@/utils/util'
  import {getAction} from '@/api/manage'
  import JEllipsis from '@/components/jeecg/JEllipsis'
  import moment from 'moment'
  import Vue from 'vue'
  export default {
    name: 'SaleProfit',
    mixins:[JeecgListMixin],
    components: {
      BillDetail,
      JEllipsis
    },
    data () {
      return {
        locale: zhCN,
        // 查询条件
        queryParam: {
          organId: undefined,
          depotId: undefined,
          organizationId: undefined,
          number: '',
          materialParam:'',
          beginTime: getPrevMonthFormatDate(3),
          endTime: getFormatDate(),
          createTimeRange: [moment(getPrevMonthFormatDate(3)), moment(getFormatDate())],
        },
        ipagination:{
          pageSize: 11,
          pageSizeOptions: ['11', '21', '31', '101', '201', '301', '1001', '2001', '3001']
        },
        cusList: [],
        depotList: [],
        orgaTree: [],
        operNumberSum: '',
        profitPriceSum: '',
        labelCol: {
          xs: { span: 24 },
          sm: { span: 10 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 14 },
        },
        pageName: 'saleProfit',
        // 默认索引
        defDataIndex:['rowIndex','number','barCode','mName','standard','model','mUnit','operNumber','unitPrice',
          'purchaseUnitPrice','salePrice','purchasePrice','profitPrice','profitRate','taxRate','sName'],
        // 默认列
        defColumns: [
          {
            dataIndex: 'rowIndex', width:40, align:"center", slots: { title: 'customTitle' },
            customRender:function (t,r,index) {
              return (t !== '合计') ? (parseInt(index) + 1) : t
            }
          },
          {
            title: '单据编号', dataIndex: 'number', width: 100,
            scopedSlots: { customRender: 'numberCustomRender' },
          },
          {title: '条码', dataIndex: 'barCode', width: 80},
          {title: '名称', dataIndex: 'mName', width: 120, ellipsis:true},
          {title: '规格', dataIndex: 'standard', width: 60, ellipsis:true},
          {title: '型号', dataIndex: 'model', width: 60, ellipsis:true},
          {title: '颜色', dataIndex: 'color', width: 50, ellipsis:true},
          {title: '品牌', dataIndex: 'brand', width: 80, ellipsis:true},
          {title: '制造商', dataIndex: 'mfrs', width: 80, ellipsis:true},
          {title: '单位', dataIndex: 'mUnit', width: 40, ellipsis:true},
          {title: '数量', dataIndex: 'operNumber', sorter: (a, b) => a.operNumber - b.operNumber, width: 50},
          {title: '销售单价', dataIndex: 'unitPrice', sorter: (a, b) => a.unitPrice - b.unitPrice, width: 60},
          {title: '成本价', dataIndex: 'purchaseUnitPrice', sorter: (a, b) => a.purchaseUnitPrice - b.purchaseUnitPrice, width: 60},
          {title: '销售金额', dataIndex: 'salePrice', sorter: (a, b) => a.salePrice - b.salePrice, width: 60},
          {title: '成本金额', dataIndex: 'purchasePrice', sorter: (a, b) => a.purchasePrice - b.purchasePrice, width: 60},
          {title: '利润', dataIndex: 'profitPrice', sorter: (a, b) => a.profitPrice - b.profitPrice, width: 60},
          {title: '利润率(%)', dataIndex: 'profitRate', sorter: (a, b) => a.profitRate - b.profitRate, width: 65},
          {title: '税率(%)', dataIndex: 'taxRate', width: 45},
          {title: '客户或会员', dataIndex: 'sName', width: 70, ellipsis:true},
        ],
        url: {
          list: "/api/plugin/sale-profit/saleProfit/getList"
        }
      }
    },
    created() {
      this.initCustomer()
      this.getDepotData()
      this.loadAllOrgaData()
      this.initColumnsSetting()
    },
    mounted () {
      this.primaryColor = Vue.ls.get(DEFAULT_COLOR)
      updateTheme(this.primaryColor)
    },
    methods: {
      moment,
      getQueryParams() {
        let param = Object.assign({}, this.queryParam, this.isorter);
        param.field = this.getQueryField();
        param.currentPage = this.ipagination.current;
        param.pageSize = this.ipagination.pageSize%10===1 ? this.ipagination.pageSize-1 : this.ipagination.pageSize;
        return param;
      },
      myHandleDetail(record) {
        findBillDetailByNumber({ number: record.number }).then((res) => {
          if (res && res.code === 200) {
            this.handleDetail(res.data, record.newType)
          }
        })
      },
      initCustomer() {
        let that = this
        findBySelectCus({}).then((res)=>{
          if(res) {
            that.cusList = res
          }
        })
      },
      getDepotData() {
        getAction('/depot/findDepotByCurrentUser').then((res)=>{
          if(res.code === 200){
            this.depotList = res.data;
          }else{
            this.$message.info(res.data);
          }
        })
      },
      loadAllOrgaData(){
        let that = this
        let params = {}
        getAllOrganizationTreeByUser(params).then((res)=>{
          if(res){
            that.orgaTree = res
          }
        })
      },
      onDateChange: function (value, dateString) {
        this.queryParam.beginTime=dateString[0]
        this.queryParam.endTime=dateString[1]
        if(dateString[0] && dateString[1]) {
          this.queryParam.createTimeRange = [moment(dateString[0]), moment(dateString[1])]
        }
      },
      onDateOk(value) {
        console.log(value);
      },
      loadData(arg) {
        //加载数据 若传入参数1则加载第一页的内容
        if (arg === 1) {
          this.ipagination.current = 1;
        }
        let params = this.getQueryParams();//查询条件
        this.loading = true;
        getAction(this.url.list, params).then((res) => {
          if (res.code===200) {
            this.dataSource = res.data.rows;
            this.ipagination.total = res.data.total;
            this.tableAddTotalRow(this.columns, this.dataSource)
            this.operNumberSum = res.data.operNumber?(res.data.operNumber).toFixed(2):res.data.operNumber
            this.profitPriceSum = res.data.profitPrice?(res.data.profitPrice).toFixed(2):res.data.profitPrice
          }
          if(res.code===505){
            this.$message.warning(res.data)
          }
          this.loading = false;
        })
      },
      exportExcel() {
        let list = []
        let head = '单据编号,条码,名称,规格,型号,颜色,品牌,制造商,单位,数量,销售单价,成本价,销售金额,成本金额,利润,利润率(%),税率(%),客户或会员'
        for (let i = 0; i < this.dataSource.length; i++) {
          let item = []
          let a = this.dataSource[i]
          item.push(a.number, a.barCode, a.mName, a.standard, a.model, a.color, a.brand, a.mfrs, a.mUnit, a.operNumber, a.unitPrice,
            a.purchaseUnitPrice, a.salePrice, a.purchasePrice, a.profitPrice, a.profitRate, a.taxRate, a.sName)
          list.push(item)
        }
        let tip = '单据日期：' + this.queryParam.beginTime + '~' + this.queryParam.endTime
        this.handleExportXlsPost('销售利润', '销售利润', head, tip, list)
      }
    }
  }
</script>

<style scoped>
  @import '~@assets/less/common.less'
</style>